package com.atues.stack;

import java.util.*;

class Solution {

    public int[] topKFrequent(int[] nums, int k) {
        //实现按照map的值来进行小顶堆
//        PriorityQueue<Map<Integer,Integer>> pq = new PriorityQueue<>((a,b) -> a.get(b) - a.get(a));
        PriorityQueue<Map.Entry<Integer,Integer>> pq = new PriorityQueue<>((a,b)->b.getValue()-a.getValue());
        Map<Integer,Integer> map = new HashMap<>();
        Arrays.stream(nums).forEach(x -> map.put(x,map.getOrDefault(x,0)+1));

        for(Map.Entry<Integer,Integer> entry : map.entrySet()){
            pq.offer(entry);
            if(pq.size() > k)
                pq.poll();
        }
        int[] res = new int[k];
        for(int i = 0; i < k; i++){
            res[i] = pq.poll().getKey();
        }
        return res;
        
    }


}